<template>
  <div class="allocate-role-dialog">
    <el-dialog
      title="分配角色"
      :visible="show"
      @close="$emit('changeDialog', false)"
      width="40%"
    >
      <el-select v-model="value" multiple placeholder="请选择">
        <el-option
          v-for="item in roles"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="$emit('changeDialog', false)">取消</el-button>
        <el-button type="primary" @click="allocateRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import { getAllRoles, allocateUserRoles } from '@/apis/role'
export default Vue.extend({
  name: 'allocate-role',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    userId: {
      type: [String, Number]
    }
  },
  data() {
    return {
      roles: [],
      value: [] as number[]
    }
  },
  created() {
    this.loadAllRoles()
  },
  methods: {
    async loadAllRoles() {
      const { data } = await getAllRoles()
      if (data.code === '000000') {
        this.roles = data.data.map((role: any) => ({
          id: role.id,
          name: role.name
        }))
      }
    },
    async allocateRole() {
      const { data } = await allocateUserRoles({ userId: this.userId, roleIdList: this.value })
      if (data.code === '000000') {
        this.$message.success('分配角色成功')
        this.$emit('changeDialog', false)
      }
    }
  }
})
</script>
<style lang="scss" scoped>
.allocate-role-dialog{
  .el-dialog{
    max-width: 300px;
  }
}

</style>
